﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Portal.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Globalization;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint.Utilities;
using ESF.SharePoint.Domain;
using Microsoft.Office.Server.ActivityFeed;
using System.Collections.Generic;
using ESF.SharePoint.Utility;
using System.Reflection;
using ESF.SharePoint.Entities;

namespace ESF.SharePoint.WebParts
{
    [ToolboxItemAttribute(false)]
    public class ExtendedActivityAggregatorWebPart : NewsFeedWebPartBase
    {
        #region Fields
        private int _maxItemsToDisplay = 10;
        private List<CustomActivityEvent> _feedsCollection;
        //private UserProfile _pageProfile;
        private EventInterval _currentInterval;

        private enum ActivityProperty
        {
            Name,
            Value,
            Link,
            Link2,
            LinkList,
            Publisher,
            Size
        }

        private enum EventInterval
        {
            NotSet,
            Today,
            Yesterday,
            Earlier
        }
        #endregion

        #region Events
        protected override void OnPreRender(object sender, EventArgs e)
        {
            base.ShowUserPicture = true;
            using (new SPMonitoredScope("ExtendedActivityAggregatorWebPart.OnPreRender"))
            {
                SocialFeeds sf = new SocialFeeds();
                _feedsCollection = sf.GetActivitiesFromMyNetworkEx();

                base.OnPreRender(e);
            }
        }

        protected override void RenderWebPart(HtmlTextWriter writer)
        {
            try
            {
                string picture = ESF.SharePoint.Helpers.Utility.UserProfileHelper.GetUserPicture();
            }
            catch (Exception ex)
            {
                string ex1 = ex.Message;
            }

            SocialFeeds sf = new SocialFeeds();
            if ((this._feedsCollection != null) && (this._feedsCollection.Count > 0))
            {
                foreach (CustomActivityEvent customEvent in this._feedsCollection)
                {
                    try
                    {
                        ActivityType type = this.ActivityManager.ActivityTypes[customEvent.ActivityTypeId];
                        ActivityTemplate template = type.ActivityTemplates[ActivityTemplatesCollection.CreateKey(customEvent.IsRolledUp)];
                        string templateFormat = template.GetTitleDisplayFormat();
                        ActivityTemplateVariable ATV = customEvent.ATV;

                        //TODO: Override template format if necessary
                        string customFormat = sf.GetActivityFormat(type);
                        if (!string.IsNullOrEmpty(customFormat))
                        {
                            templateFormat = customFormat;
                        }
                        
                        if (!string.IsNullOrEmpty(templateFormat) && ((ATV != null) && (ATV.Publisher != null)))
                        {
                            this.RenderEvent(writer, templateFormat, customEvent);
                        }
                        continue;
                    }
                    catch (Exception ex)
                    {
                        //ULS.SendTraceTag(0x656c3863, ULSCat.msoulscat_SPS_UserProfiles, ULSTraceLevel.High, "profileUI: Error rendering event: " + exception.ToString());
                        continue;
                    }
                }
            }

        }
        #endregion

        #region Methods
        void RenderEvent(HtmlTextWriter writer, string format, CustomActivityEvent customEvent)
        {
            DateTime lastUpdateTime = customEvent.LastUpdateTime;
            DateTime localTime = SPContext.Current.Web.RegionalSettings.TimeZone.UTCToLocalTime(lastUpdateTime);
            EventInterval dateInterval = this.GetDateInterval(localTime);
            if ((this._currentInterval != dateInterval) && ((this._currentInterval != EventInterval.NotSet) || (dateInterval != EventInterval.Earlier)))
            {
                this._currentInterval = dateInterval;
                writer.Write("<div class=\"ms-newsfeedheaderrow\">");
                writer.Write(GetEventIntervalString(this._currentInterval));
                writer.Write("</div>");
            }

            writer.Write("<div class=\"ms-newsfeedeventrow\">");
            if (this.ShowUserPicture)
            {
                string picture = customEvent.ATV.Publisher.Picture;
                picture = ESF.SharePoint.Utility.ESFUtility.GetUserPicture(picture);
                writer.Write("<div class=\"ms-newsfeedeventimage\">");
                string str2 = "<div class=\"ms-profilepicture ms-smallthumbnailimage\">";
                str2 = (((str2 + "<a href=\"" + SPHttpUtility.HtmlUrlAttributeEncode(SPHttpUtility.UrlPathEncode(customEvent.ATV.Publisher.Href, false)) + "\">") + "<img src='") + SPHttpUtility.HtmlUrlAttributeEncode(SPHttpUtility.NoEncode(picture)) + "' alt=''>") + "</img> </a>" + "</div>";
                writer.Write(str2);
                writer.Write("</div>");
            }
            writer.Write("<div class=\"ms-newsfeedeventtext\">");
            writer.Write(ReplacePlaceHolder(format, customEvent));
            writer.Write("</div>");
            writer.Write("</div>");
        }

        private string ReplacePlaceHolder(string format, CustomActivityEvent customEvent)
        {
            string activity = format;
            activity = activity.Replace("{Publisher}", GetActivityProperty(ActivityProperty.Publisher, customEvent));
            activity = activity.Replace("{Name}", GetActivityProperty(ActivityProperty.Name, customEvent));
            activity = activity.Replace("{Value}", GetActivityProperty(ActivityProperty.Value, customEvent));
            activity = activity.Replace("{Link}", GetActivityProperty(ActivityProperty.Link, customEvent));
            activity = activity.Replace("{Link2}", GetActivityProperty(ActivityProperty.Link2, customEvent));
            activity = activity.Replace("{List}", GetActivityProperty(ActivityProperty.LinkList, customEvent));
            activity = activity.Replace("{Size}", GetActivityProperty(ActivityProperty.Size, customEvent));
            
            return activity;
        }

        private string GetActivityProperty(ActivityProperty prop, CustomActivityEvent customEvent)
        {
            string value = null;
            switch (prop)
            {
                case ActivityProperty.Publisher:
                    value = ActivityTemplateVariable.PublisherToString("", customEvent.ATV, ContentType.Html, CultureInfo.CurrentUICulture);
                    break;
                case ActivityProperty.Name:
                    value = ActivityTemplateVariable.NameToString("", customEvent.ATV, ContentType.Html, CultureInfo.CurrentUICulture);
                    break;
                case ActivityProperty.Value:
                    value = ActivityTemplateVariable.ValueToString("", customEvent.ATV, ContentType.Html, CultureInfo.CurrentUICulture);
                    break;
                case ActivityProperty.Link:
                    value = ActivityTemplateVariable.LinkToString("", customEvent.ATV, ContentType.Html, CultureInfo.CurrentUICulture);
                    break;
                case ActivityProperty.Link2:
                    value = ActivityTemplateVariable.Link2ToString("", customEvent.ATV, ContentType.Html, CultureInfo.CurrentUICulture);
                    break;
                case ActivityProperty.LinkList:
                    value = ActivityTemplateVariable.ListToString("", customEvent.ATV, ContentType.Html, CultureInfo.CurrentUICulture);
                    break;
                case ActivityProperty.Size:
                    value = ActivityTemplateVariable.SizeToString("", customEvent.ATV, ContentType.Html, CultureInfo.CurrentUICulture);
                    break;
            }

            if (customEvent.Modified)
                value = HttpUtility.HtmlDecode(value);

            return value;
        }

        private EventInterval GetDateInterval(DateTime localTime)
        {
            if (localTime.Date == this.Today.Date)
            {
                return EventInterval.Today;
            }
            if (localTime.Date == this.Today.Date.AddDays(-1.0))
            {
                return EventInterval.Yesterday;
            }
            return EventInterval.Earlier;
        }

        private static string GetEventIntervalString(EventInterval interval)
        {
            string label;
            string date;
            switch (interval)
            {
                case EventInterval.Today:
                    label = "Today"; //StringResourceManager.GetString(LocStringId.DateInterval_Text_Today);
                    date = SPUtility.FormatDate(SPContext.Current.Web, DateTime.Now.ToUniversalTime(), SPDateFormat.MonthDayOnly);
                    break;

                case EventInterval.Yesterday:
                    label = "Yesterday"; //StringResourceManager.GetString(LocStringId.DateInterval_Text_Yesterday);
                    date = SPUtility.FormatDate(SPContext.Current.Web, DateTime.Now.AddDays(-1.0).ToUniversalTime(), SPDateFormat.MonthDayOnly);
                    break;

                default:
                    label = "Earlier"; //StringResourceManager.GetString(LocStringId.DateInterval_Text_Earlier);
                    date = string.Empty;
                    break;
            }
            return ("<span>" + SPHttpUtility.HtmlEncode(label) + " </span>" + SPHttpUtility.HtmlEncode(date));
        }
        #endregion

        #region Properties
        [Resources("QueryResults_MaxItem_PropertyName", "Webpart__Custome_Property_Text", "QueryResults_MaxItem_PropertyDescription"), WebPartStorage(Storage.Shared), DefaultValue(10)]
        public override int MaxItemsToDisplay
        {
            get
            {
                return this._maxItemsToDisplay;
            }
            set
            {
                if (value < 0)
                {
                    this._maxItemsToDisplay = 0;
                }
                else if (value > 100)
                {
                    this._maxItemsToDisplay = 100;
                }
                else
                {
                    this._maxItemsToDisplay = value;
                }
            }
        }

        private DateTime m_dtToday;
        private DateTime Today
        {
            get
            {
                if (this.m_dtToday == DateTime.MinValue)
                {
                    this.m_dtToday = SPContext.Current.Web.RegionalSettings.TimeZone.UTCToLocalTime(DateTime.Now.ToUniversalTime());
                }
                return this.m_dtToday;
            }
        }
        #endregion

    }

}
